package com.tju.resource.business.log;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tju.resource.common.ServiceException;
import com.tju.resource.mapper.LogLoginMessageMapper;
import com.tju.resource.mapper.LogOperationMapper;
import com.tju.resource.model.log.LogLoginMessage;
import com.tju.resource.model.log.LogOperation;
import com.tju.resource.model.log.LoginLogTool;
import com.tju.resource.result.Result;
import com.tju.resource.result.ResultEnum;
import com.tju.resource.result.ResultUtil;
import com.tju.resource.tool.tool.ChineseExceptionUtils;
import com.tju.resource.tool.tool.ClientParameters;
import com.tju.resource.tool.tool.IpUtil;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 日志处理器
 *
 * @Author CLS
 * @Date 2022/4/22 17:49
 */
@Slf4j
@Service
public class LogProcessor {

    @Autowired
    private ChineseExceptionUtils zh_ch;

    @Autowired
    private LogLoginMessageMapper loginMessageMapper;
    @Autowired
    private LogOperationMapper operationMapper;

    /**
     * 获取登录日志
     *
     * @param parameter
     * @return
     */
    public Result<Object> getLoginLog(ClientParameters.Log parameter) {
        try {
            QueryWrapper<LogLoginMessage> wrapper = new QueryWrapper<>();
            if (parameter.getLoginStartDate() != null && !parameter.getLoginStartDate().equals("") && parameter.getLoginEndDate() != null && !parameter.getLoginEndDate().equals("")) {
                wrapper.between("login_date", parameter.getLoginStartDate(), parameter.getLoginEndDate());
            }
            wrapper.orderByDesc("id");
            Page<LogLoginMessage> page = new Page<>(parameter.getPage(), parameter.getLimit());
            IPage<LogLoginMessage> iPage = loginMessageMapper.selectPage(page, wrapper);
            return ResultUtil.success(ResultEnum.SUCCESS, iPage.getRecords(), iPage.getTotal());
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ServiceException(zh_ch.AbnormalOperation);
        }
    }

    /**
     * 获取操作日志
     *
     * @param parameter
     * @return
     */
    public Result<Object> getOperationLog(ClientParameters.Log parameter) {
        try {
            QueryWrapper<LogOperation> wrapper = new QueryWrapper<>();
            if (parameter.getLoginStartDate() != null && parameter.getLoginStartDate() != "" && parameter.getLoginEndDate() != null && parameter.getLoginEndDate() != "") {
                wrapper.between("operation_date", parameter.getLoginStartDate(), parameter.getLoginEndDate());
            }
            wrapper.orderByDesc("id");
            Page<LogOperation> page = new Page<>(parameter.getPage(), parameter.getLimit());
            IPage<LogOperation> iPage = operationMapper.selectPage(page, wrapper);
            return ResultUtil.success(ResultEnum.SUCCESS, iPage.getRecords(), iPage.getTotal());
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ServiceException(zh_ch.AbnormalOperation);
        }
    }

    /**
     * 写入登录退出日志
     *
     * @param logTool 用户名，登录状态，操作信息
     */
    public void writeLogLog(LoginLogTool logTool, HttpServletRequest request) {
        loginMessageMapper.insert(Operating.encapsulateLoginLogData(logTool, request));
    }

    public static class Operating {

        /**
         * 封装登录日志资料
         *
         * @param logTool
         */
        public static LogLoginMessage encapsulateLoginLogData(LoginLogTool logTool, HttpServletRequest request) {
            UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("user-agent"));
            String ip = IpUtil.getIpAddr(request);
            logTool.setIp(ip);
            //地点
            String place = IpUtil.getIpRegion(ip);
            place = (place.contains("内网IP")) ? "内网IP" : place;
            logTool.setPlace(place);
            //浏览器类型
            logTool.setBrowser(userAgent.getBrowser().toString());
            //操作系统类型
            logTool.setOperatingSystem(userAgent.getOperatingSystem().getName());
            return new LogLoginMessage(JSONUtil.parseObj(logTool).toString());
        }

    }
}
